//
//  GAPhotoGroupView.swift
//  PMS
//
//  Created by 何海涛 on 15/10/20.
//  Copyright © 2015年 途家. All rights reserved.
//

import Foundation

@objc protocol GAAutoScrollViewDelegate: NSObjectProtocol{
    func numbersOfPages()->Int
    func imageNameOfIndex(_ index: Int) -> String!
    @objc optional func didSelectedIndex(_ index: Int)
    @objc optional func currentIndexDidChange(_ index: Int)
}

open class GAPhotoGroupView : UIScrollView,GAAutoScrollViewDelegate {
    
    public var imageArray : [String]?
    fileprivate var imageThumbnailArray : [String]?
    fileprivate var images : [(UIImageView,UIButton)] = [(UIImageView,UIButton)]()
    fileprivate lazy var imageCount : UIButton = {
        let btn = UIButton(frame:CGRect(x:self.frame.width - self.imgThumbWidth,y: 0, width: self.imgThumbWidth, height: self.frame.height))
        btn.isHidden = true
        btn.layer.borderWidth = CommonDefine.kPixel
        btn.layer.borderColor =  UIColor(red: 0.863, green: 0.863, blue: 0.863, alpha: 0.8).cgColor
        btn.backgroundColor = UIColor.white
        btn.addTarget(self, action: #selector(self.jumpToDetail(selectIndex:)), for: .touchUpInside)
        btn.titleLabel!.font = VS.font12
        btn.setTitleColor(CommonColors.c_999999, for: UIControl.State())
        self.addSubview(btn)
        return btn;
    }()
    var photoView : (GAPhotoView,UIButton)?
    
    fileprivate let imgThumbWidth : CGFloat = 68
    fileprivate let imgMargin : CGFloat = 6
    
    public func loadData(_ imgs : [String], imgThumbnails : [String]) {
        if imgs.count == 0 { return }
        if imgs.count != imgThumbnails.count { return } // error data
        self.imageArray = imgs
        if (!arrayEqual(imgThumbnails, self.imageThumbnailArray ?? [String]())) {
            initThumbnails(imgThumbnails)
        }
    }
    
    public func initThumbnails(_ imgs : [String]) {
        if imageThumbnailArray != nil {
            self.contentOffset = CGPoint(x: 0, y: 0) // reset position if reuse this control
        }
        self.contentSize = CGSize(width: CGFloat(imgs.count) * imgThumbWidth + CGFloat(imgs.count - 1) * imgMargin, height: self.frame.height)
        var startX : CGFloat = 0
        for (index,item) in imgs.enumerated() {
            if ( self.frame.width - startX < self.imgThumbWidth * 2 + imgMargin ){
                self.imageCount.isHidden = false
                self.imageCount.setTitle("共\(self.imageArray?.count ?? 0)张", for: UIControl.State())
                self.imageCount.x = startX
                return
            }
            var view : UIImageView
            if images.count > index {
                view = images[index].0
            } else {
                view = UIImageView(frame: CGRect(x: startX, y: 0, width: imgThumbWidth, height: self.frame.height))
                let btnImage = UIButton(frame: view.frame)
                btnImage.addTarget(self, action: #selector(GAPhotoGroupView.btnImage_Touched(_:)), for: .touchUpInside)
                images.append((view,btnImage))
                view.layer.borderWidth = CommonDefine.kPixel
                view.layer.borderColor =  UIColor(red: 0.863, green: 0.863, blue: 0.863, alpha: 0.8).cgColor
                self.addSubview(view)
                self.addSubview(btnImage)
            }
            view.image = UIImage(named: "small_image_default")
            view.setURL(item)
            startX = startX + imgThumbWidth + imgMargin
        }
        if images.count > imgs.count {
            for index in imgs.count ..< images.count {
                let (i,b) = images[index]
                i.removeFromSuperview()
                b.removeFromSuperview()
            }
        }
        self.imageThumbnailArray = imgs
    }
    public func numbersOfPages()->Int {
        return self.imageArray!.count
    }
    public func imageNameOfIndex(_ index: Int) -> String {
        return self.imageArray![index]
    }
    @objc public func btnImage_Touched(_ sender : UIButton) {
        let selectIndex = images.index(where: { i in i.1 == sender })
        if selectIndex == nil { return }
//        if photoView == nil {
//            let imageHeight : CGFloat = 180
//            let photo = GAPhotoView(frame: CGRectMake(8, (CommonDefine.kScreenHeight - imageHeight)/2, CommonDefine.kScreenWidth - 16, imageHeight), data: nil, zoom: false, scaleImage: false)
//            photo.layer.cornerRadius = 5
//            photo.layer.masksToBounds = true
//            photo.layer.borderWidth = 5
//            photo.layer.borderColor = CommonColors.c_aaaaaa.CGColor
//            let bg = UIButton(frame: CGRectMake(0, 64, CommonDefine.kScreenWidth, CommonDefine.kScreenHeight))
//            bg.backgroundColor = CommonColors.c_252733_30
//            bg.addTarget(self, action: "bg_Touched", forControlEvents: .TouchDown)
//            photoView = (photo,bg)
//        }
//        photoView?.0.dataArray = self.imageArray
//        photoView?.0.setIndex(Int(selectIndex!.value))
//        let topView : UITableView? = getClosestSuperViewOf()
//        topView?.superview?.addSubview(photoView!.1)
//        topView?.superview?.addSubview(photoView!.0)
        
        
        jumpToDetail(selectIndex: selectIndex!);
    }
    
    @objc open func jumpToDetail(selectIndex: Int = 0) {
        
    }
    
//    func bg_Touched() {
//        photoView?.0.removeFromSuperview()
//        photoView?.1.removeFromSuperview()
//    }
    
    fileprivate func arrayEqual(_ lhs : [String], _ rhs : [String]) -> Bool {
        if lhs.count != rhs.count { return false }
        for (i,v) in lhs.enumerated() {
            let rv = rhs[i]
            if v != rv { return false }
        }
        return true
    }
}
